package com.bwhx.eruler.filter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TokenFilter extends OncePerRequestFilter {

	private String token;
	
	Log log = LogFactory.getLog(this.getClass());

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String uri = request.getRequestURI();
		String header = request.getHeader("Content-type");
		if (uri.contains("page.")||uri.contains("uploadlog") || uri.contains("download/app")||uri.contains("uploadFile")||uri.contains("csharpclient.")) {//如果是后台管理页面请求或者是C#客户端传来的请求
			filterChain.doFilter(request, response);
		}

		// uri中包含ashx时才进行过滤
		else if (uri.endsWith(".ashx")) {
			
			//log.info("======================================================"+new Date().toLocaleString()+"================================================");
			log.info("======================================================"+new Date().toLocaleString()+"================================================");	
				
				//log.info(header);
			log.info(header);
				//当请求参数是以json方式传过来时（Apple）
				//if(header.contains("application/json")){
			
				//解析json，setAttribute
				InputStream in = request.getInputStream();
				 
				 //这里接受到客户端传过来的数据 是json字符类型
				BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
			    StringBuilder sb = new StringBuilder();
			    String line;
			    while((line=reader.readLine())!=null){
			        sb.append(line);
			    }
			    String para = sb.toString();
			    request.setAttribute("params", para);
			   // log.info(para);
			    log.info(para);
			    if(para!=null){
			    	 //{"username":"yang","pwd":"123456","token":"123wfzaaSD*"}
				    if(header != null && !header.isEmpty() && header.contains("application/json")){  //苹果
					    ObjectMapper objectMapper = new ObjectMapper();;
					    LinkedHashMap<String, Object> map = objectMapper.readValue(para, LinkedHashMap.class);
					    for(Map.Entry<String, Object> entry:map.entrySet()){
					    	request.setAttribute(entry.getKey(), entry.getValue());
					    }
					}else{ //安卓
						//username=111&pwd=222
						String[] kVs = para.trim().replace(" ", "").split("&");
						for (String str : kVs) {
							String[] kV = str.split("=");
							if(kV.length == 2){
								if(kV[1].startsWith("\"")){
									String kv1=kV[1].substring(1, kV[1].length()-1);
									request.setAttribute(kV[0].replace("\"", ""), kv1);
								}else{
									request.setAttribute(kV[0].replace("\"", ""), kV[1]);
								}
							}
						}
					}
			    }
			   
			    

			    token = ((String) request.getAttribute("token"));
				if (null==token) {
					// 设置request和response的字符集，防止乱码
					
					response.setCharacterEncoding("UTF-8");
					response.setHeader("Content-type","application/json;charset=UTF-8" );
					PrintWriter out = response.getWriter();
					String responseJson = "{\"status\":\"0\",\"meg\":\"token参数不全！\"}";
					out.print(responseJson);
					
				} else {
				    token = ((String) request.getAttribute("token")).replace("\"", "");

					if (token.equals("123wfzaaSD*")) {
						// 如果token值是对的
						filterChain.doFilter(request, response);
					}
					else {
						// 设置request和response的字符集，防止乱码
						
						response.setCharacterEncoding("UTF-8");
						response.setHeader("Content-type","application/json;charset=UTF-8" );
						PrintWriter out = response.getWriter();
						String responseJson = "{\"status\":\"0\",\"meg\":\"非法请求！\"}";
						out.print(responseJson);
					}
				
					
				}
			}else {
			// 如果uri中不包含ashx，则继续
			filterChain.doFilter(request, response);
		}
	}

}
